<template>
  <div v-loading="loading" class="manage-coupon">
    <el-collapse-transition>
      <div v-show="!isShowDetail">
        <div class="top">
          <!-- <div class="flexRBC">
            <div class="app-main-top-box"><div class="title">券管理</div></div>
            <el-button v-if="!$store.getters.banBtnList.includes('BTN_MCH_COUPON_MANAGER_AND_PUT_ON')" size="medium" type="primary" round @click="openSyncWxPayCoupon">
              同步微信支付券
            </el-button>
          </div> -->

          <div class="create">
            <div class="card">
              <div class="title">
                <div>满减券</div>
                <el-button type="primary" @click="jumpAdd('cash')">创建</el-button>
              </div>
              <div class="p">可抵扣部分金额，支持多张叠加使用</div>
            </div>
            <div class="card">
              <div class="title">
                <div>折扣券</div>
                <el-button type="primary" @click="jumpAdd('discount')">创建</el-button>
              </div>
              <div class="p">按折扣计算抵扣金额，支持最大抵扣上限</div>
            </div>
            <div class="card">
              <div class="title">
                <div>兑换券</div>
                <el-button type="primary" @click="jumpAdd('exchange')">创建</el-button>
              </div>
              <div class="p">只支持核销，用于一些兑换场景，不支持线上订单核销</div>
            </div>
          </div>
          <div class="tab">
            <el-tabs v-model="filterForm.status" @tab-click="changeTab">
              <el-tab-pane label="生效中" name="1" />
              <!-- <el-tab-pane label="报名中" name="6" /> -->
              <!-- <el-tab-pane label="已暂停" name="3" /> -->
              <el-tab-pane label="已结束" name="2" />
              <el-tab-pane label="草稿箱" name="3" />
              <!-- <el-tab-pane label="已过期" name="5" /> -->
            </el-tabs>
          </div>
        </div>

        <!-- 列表 -->
        <div class="content-main app-main-content-box">
          <!--筛选-->
          <el-form ref="filterForm" :inline="true" :model="filterForm" label-width="70px" size="small">
            <el-form-item label="名称：" prop="couponName"><el-input v-model="filterForm.couponName" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="批次：" prop="stockId"><el-input v-model="filterForm.stockId" placeholder="请输入" clearable /></el-form-item>
            <el-form-item label="类型：" prop="types">
              <el-select
                v-model="filterForm.types"
                filterable
                multiple
                collapse-tags
                placeholder="请选择"
                class="w-400"
                @change="val => idsChange(val, 'couponType')"
              >
                <el-option label="所有类型" value />
                <el-option v-for="(v, k) in couponTypeOptions" :key="k" :label="v" :value="k" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="filterForm.status === '1'" label="状态：" prop="shStatus">
              <el-select v-model="filterForm.shStatus" placeholder="请选择" class="w-400">
                <el-option label="所有" value />
                <el-option label="已上架" value="1" />
                <el-option label="已下架" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="商户：" prop="merchTypes">
              <el-select v-model="filterForm.merchTypes" placeholder="请选择" class="w-400">
                <el-option label="所有" value />
                <el-option label="本商户" value="2" />
                <el-option label="商圈" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label-width="0">
              <el-button type="primary" round @click="submitFilterForm">查 询</el-button>
              <el-button round @click="resetFilterForm">重 置</el-button>
            </el-form-item>
          </el-form>

          <!-- <div>
						<el-row v-if="list.length > 0" :gutter="30" type="flex">
							<el-col v-for="(v, i) in list" :key="i" :xs="12" :sm="8" :md="8" :lg="8" :xl="6" class="coupon-card">
								<div v-if="v.couponTag == 1" class="coupon-labelType">商圈券</div>
								<el-card shadow="hover" @click.native="showDetail(v)">
									<div class="coupon-content">
										<div class="coupon-base">
											<div class="left">
												<img v-if="v.icon" :src="fileBaseUrl + v.icon" alt />
												<el-image v-else :src="'static/icon/coupon/i-coupon-' + v.couponType + '.png'" fit="fill" />
											</div>
											<div class="right">
												<div class="name app-line-one">{{ v.couponName }}</div>
												<div class="type app-line-one">批次号：{{ v.id }} | {{ couponTypeOptions[v.couponType] }}</div>
											</div>
										</div>
										<div class="coupon-detail">
											<div v-if="couponTypeGroup.cash.includes(v.couponType)" class="cash">{{ v.denomination / 100 }}元</div>
											<div v-if="couponTypeGroup.discount.includes(v.couponType)" class="discount">{{ v.discountPercent / 10 }}折</div>
											<div v-if="couponTypeGroup.exchange.includes(v.couponType)" class="exchange">{{ v.exchangeThings }}</div>
											<div v-if="couponTypeGroup.cash.includes(v.couponType)" class="describe">
												订单满{{ v.transactionMinimum / 100 }}元可用{{ v.maxUseNum && v.maxUseNum > 1 ? '，最多叠加' + v.maxUseNum + '张' : '' }}
											</div>
										</div>
										<div class="coupon-more">
											<div class="date">有效期：{{ v.startTime + ' ~ ' + v.endTime }}</div>
											<div class="belong">归属人：{{ `${v.belongMerchantName}（${v.belongMerchant}）` }}</div>
										</div>
										<div v-if="v.status === 1" class="coupon-status">
											<div v-if="!v.channelSync && ['cash_wx_busi', 'discount_wx_busi'].includes(v.couponType) && v.syncMsg" class="app-text-color-danger">
												券渠道同步失败，请检查
												<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
													<div slot="content">{{ v.syncMsg }}</div>
													<i class="el-icon-warning" />
												</el-tooltip>
											</div>
											<div v-else-if="!v.channelSync && ['cash_wx_busi', 'discount_wx_busi'].includes(v.couponType)" class="app-text-color-warning">
												该批次需同步券渠道
											</div>
											<div v-else class="app-text-color-primary">该批次激活即可使用</div>
										</div>
									</div>
								</el-card>
							</el-col>
						</el-row>
						<div v-else class="empty-text">暂无数据</div>
					</div> -->

          <el-table v-if="filterForm.status === '1'" key="1" :data="tableData" border>
            <el-table-column prop="id" label="批次号" />
            <el-table-column prop="couponTag" label="适用商户">
              <template slot-scope="scope">
                {{ scope.row.couponTag === 2 ? '本商户' : '商圈' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponType" label="类型">
              <template slot-scope="scope">
                {{ scope.row.couponType === 'cash' ? '满减券' : scope.row.couponType === 'discount' ? '折扣券' : '兑换券' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponName" label="名称" />
            <el-table-column prop="conten" label="优惠内容" width="150">
              <template slot-scope="scope">
                {{
                  scope.row.couponType === 'cash'
                    ? `满${scope.row.transactionMinimum / 100}元减${scope.row.denomination / 100}元`
                    : scope.row.couponType === 'discount'
                      ? `满${scope.row.transactionMinimum / 100}元打${scope.row.discountPercent / 10}折`
                      : scope.row.exchangeThings
                }}
              </template>
            </el-table-column>
            <el-table-column prop="receiveCount" label="领取数" />
            <el-table-column prop="verifyCount" label="核销数" />
            <el-table-column prop="time" label="有效期" width="300">
              <template slot-scope="scope">
                {{ scope.row.startTimeDetail }} ~ {{ scope.row.endTimeDetail }}
              </template>
            </el-table-column>
            <el-table-column prop="upStatus" label="领券中心状态">
              <template slot="header" slot-scope="scope">
                <span>领券中心状态</span>
                <el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
                  <div slot="content">
                    <p>已上架状态表示券在小程序领券中心，用户可在小程序领券中心自主领取，商户也可以单独发放给用户。</p>
                    <p style="margin-top: 8px;">已下架状态表示券不在小程序领券中心，用户不可自主领取，但是商户可单独发放给用户。</p>
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                {{ scope.row.upStatus ? '已上架' : '已下架' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button v-if="scope.row.upStatus" type="text" size="small" @click="handleInto(scope.row, 'off')">下架</el-button>
                <el-button v-if="!scope.row.upStatus" type="text" size="small" @click="handleInto(scope.row, 'shelf')">上架</el-button>
                <el-button type="text" size="small" @click="handleInto(scope.row, 'stop')">终止</el-button>
                <el-button type="text" size="small" @click="handleInto(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table v-if="filterForm.status === '2'" key="2" :data="tableData" border>
            <el-table-column prop="id" label="批次号" />
            <el-table-column prop="couponTag" label="适用商户">
              <template slot-scope="scope">
                {{ scope.row.couponTag === 2 ? '本商户' : '商圈' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponType" label="类型">
              <template slot-scope="scope">
                {{ scope.row.couponType === 'cash' ? '满减券' : scope.row.couponType === 'discount' ? '折扣券' : '兑换券' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponName" label="名称" />
            <el-table-column prop="conten" label="优惠内容" width="150">
              <template slot-scope="scope">
                {{
                  scope.row.couponType === 'cash'
                    ? `满${scope.row.transactionMinimum / 100}元减${scope.row.denomination / 100}元`
                    : scope.row.couponType === 'discount'
                      ? `满${scope.row.transactionMinimum / 100}元打${scope.row.discountPercent / 10}折`
                      : scope.row.exchangeThings
                }}
              </template>
            </el-table-column>
            <el-table-column prop="receiveCount" label="领取数" />
            <el-table-column prop="verifyCount" label="核销数" />
            <el-table-column prop="time" label="有效期" width="300">
              <template slot-scope="scope">
                {{ scope.row.startTimeDetail }} ~ {{ scope.row.endTimeDetail }}
              </template>
            </el-table-column>
            <el-table-column prop="endOperation" label="备注">
              <template slot-scope="scope">
                {{ scope.row.endOperation === 1 ? '自动结束' : '手动结束' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleEnd(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-table v-if="filterForm.status === '3'" key="3" :data="tableData" border>
            <el-table-column prop="id" label="批次号" />
            <el-table-column prop="couponTag" label="适用商户">
              <template slot-scope="scope">
                {{ scope.row.couponTag === 2 ? '本商户' : '商圈' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponType" label="类型">
              <template slot-scope="scope">
                {{ scope.row.couponType === 'cash' ? '满减券' : scope.row.couponType === 'discount' ? '折扣券' : '兑换券' }}
              </template>
            </el-table-column>
            <el-table-column prop="couponName" label="名称" />
            <el-table-column prop="conten" label="优惠内容" width="150">
              <template slot-scope="scope">
                {{
                  scope.row.couponType === 'cash'
                    ? `满${scope.row.transactionMinimum / 100}元减${scope.row.denomination / 100}元`
                    : scope.row.couponType === 'discount'
                      ? `满${scope.row.transactionMinimum / 100}元打${scope.row.discountPercent / 10}折`
                      : scope.row.exchangeThings
                }}
              </template>
            </el-table-column>
            <el-table-column prop="time" label="有效期" width="300">
              <template slot-scope="scope">
                {{ scope.row.startTimeDetail }} ~ {{ scope.row.endTimeDetail }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleDraft(scope.row, 'enable')">启用</el-button>
                <el-button type="text" size="small" @click="handleDraft(scope.row, 'dele')">删除</el-button>
                <el-button type="text" size="small" @click="handleDraft(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />
        </div>
      </div>
    </el-collapse-transition>

    <!-- 效果详情 -->
    <el-collapse-transition><CouponInfo v-if="isShowDetail" ref="couponInfo" /></el-collapse-transition>

    <DialogSyncWxPayCoupon ref="dialogSyncWxPayCoupon" />

    <DialogEnable ref="dialogEnable" />
  </div>
</template>

<script>
import DialogSyncWxPayCoupon from './components/DialogSyncWxPayCoupon'
import CouponInfo from './components/CouponInfo'
import DialogEnable from './components/DialogEnable'
import { couponList, searchCoupon, newUpAndDown, stopCoupon, deleteDraft } from '../../api/coupon'
import { mapActions, mapGetters } from 'vuex'

export default {
  components: {
    CouponInfo,
    DialogSyncWxPayCoupon,
    DialogEnable
  },
  data() {
    return {
      // 配置
      couponTypeOptions: {
        cash: '满减券',
        discount: '折扣券',
        exchange: '兑换券'
      },
      couponTypeGroup: {
        cash: ['cash'],
        discount: ['discount'],
        exchange: ['exchange']
      },
      // 状态
      loading: false,
      isShowDetail: false,
      // 数据
      list: [], // 列表
      lastCouponTypesIds: [],
      couponTypesIds: ['', 'cash', 'discount', 'exchange'],
      filterForm: {
        status: '1',
        couponName: null,
        stockId: null,
        types: [],
        merchTypes: '',
        shStatus: ''
      },
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      tableData: []
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  activated() {
    this.isShowDetail = false
    this.fetchData()
    this.getActiveMaIsOnline()
  },
  created() {},
  mounted() {
    // this.fetchData()
    // this.getActiveMaIsOnline()
  },
  methods: {
    /**
		 *  获取数据
		 */
    // 获取小程序是否上线
    ...mapActions(['getAuthMa']),
    getActiveMaIsOnline() {
      this.getAuthMa()
    },

    // 列表
    fetchData() {
      this.loading = true
      // 编辑券的保存
      if (this.$route.params.saveType === 'on') {
        this.filterForm.status = '1'
        this.paginationConfig.total = 0
        this.paginationConfig.page = 1
      } else if (this.$route.params.saveType === 'draft') {
        this.filterForm.status = '3'
        this.paginationConfig.total = 0
        this.paginationConfig.page = 1
      }

      const params = this.filterForm
      // couponList(params)
      // 	.then(res => {
      // 		this.list = res.data;
      // 	})
      // 	.catch(err => {})
      // 	.finally(() => {
      // 		this.loading = false;
      // 	});
      params.pageSize = this.paginationConfig.pageSize
      params.pageNum = this.paginationConfig.page
      params.name = this.filterForm.couponName
      params.couponId = this.filterForm.stockId
      params.couponTag = this.filterForm.merchTypes
      params.type = this.filterForm.types
      params.shelfStatus = this.filterForm.shStatus
      searchCoupon(params)
        .then(res => {
          this.tableData = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .catch(err => {})
        .finally(() => {
          this.loading = false
        })
    },

    /**
		 * 按钮组
		 */
    // 切换tab
    changeTab(e) {
      if (e.name == 6) {
        this.filterForm.status = '6'
      }
      this.$route.params.saveType = ''
      this.fetchData()
    },

    // 查询
    submitFilterForm() {
      this.fetchData(1)
    },

    // 重置
    resetFilterForm() {
      this.$refs.filterForm.resetFields()
      this.fetchData(1)
    },

    // 获取详情
    showDetail(row) {
      this.isShowDetail = true
      this.$nextTick(() => {
        this.$refs.couponInfo.open(row).then(res => {
          this.fetchData()
          this.isShowDetail = false
        })
      })
    },

    openSyncWxPayCoupon() {
      this.$refs.dialogSyncWxPayCoupon.open().then(() => {})
    },

    //

    /**
		 * 状态组
		 */
    // 多选改变
    idsChange(val, type) {
      let lastIdsType = ''
      let idsType = ''
      let allIds = ''
      switch (type) {
        case 'couponType':
          lastIdsType = 'lastCouponTypesIds'
          idsType = 'types'
          allIds = 'couponTypesIds'
          break
      }
      const lastVal = this[lastIdsType]
      if (val.includes('')) {
        this.filterForm[idsType] = this[allIds]
      }
      if (lastVal.includes('') && !val.includes('')) {
        this.filterForm[idsType] = []
      }
      if (lastVal.includes('') && val.includes('')) {
        val.splice(val.findIndex(v => v === ''), 1)
        this.filterForm[idsType] = val
      }
      if (!lastVal.includes('') && !val.includes('')) {
        if (val.length === this[allIds].length - 1) {
          this.filterForm[idsType] = [''].concat(val)
        }
      }
      this[lastIdsType] = this.filterForm[idsType]
    },
    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },
    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    handleInto(row, type) {
      if (type === 'off') {
        const confirmText = ['是否下架当前优惠券？', '注：下架后用户不可在小程序自主领取，但商户后台可给用户发放']
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.newUpAndDownFun(row, type)
          })
          .catch(() => {})
      } else if (type === 'shelf') {
        const confirmText = ['是否上架当前优惠券？', '注：上架后用户可在小程序领取']
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.newUpAndDownFun(row, type)
          })
          .catch(() => {})
      } else if (type === 'stop') {
        const confirmText = ['是否终止当前优惠券？', '注：终止后将不可再次使用，并不影响已发放券的使用']
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.stopCouponFun(row)
          })
          .catch(() => {})
      } else {
        this.showDetail(row)
      }
    },
    handleEnd(row) {
      this.showDetail(row)
    },
    handleDraft(row, type) {
      if (type === 'enable') {
        this.$refs.dialogEnable.open(row).then(res => {
          this.fetchData()
        })
      } else if (type === 'dele') {
        const confirmText = ['是否删除当前优惠券？', '注：删除后不可修复，请谨慎操作。']
        const newDatas = []
        const h = this.$createElement // 先用$createElement创建h函数。
        for (const i in confirmText) {
          newDatas.push(h('p', confirmText[i]))
        }
        this.$confirm('提示', {
          title: '提示',
          message: h('div', null, newDatas),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteDraftFun(row)
          })
          .catch(() => {})
      } else {
        this.showDetail(row)
      }
    },

    // 上下架
    newUpAndDownFun(row, type) {
      const { id } = row
      const params = {
        // 批次号
        couponId: id,
        // 上下架操作 1-上架 2-下架
        operation: type === 'off' ? 2 : 1
      }
      newUpAndDown(params).then(res => {
        this.fetchData()
      })
    },
    // 终止
    stopCouponFun(row) {
      const { id } = row
      const params = {
        // 批次号
        stockId: id,
        status: 3
      }
      stopCoupon(params).then(res => {
        this.fetchData()
      })
    },
    // 删除
    deleteDraftFun(row) {
      const { id } = row
      const params = {
        // 批次号
        couponId: id
      }
      deleteDraft(params).then(res => {
        this.fetchData()
      })
    },

    jumpAdd(couponType) {
      this.$router.push({
        name: 'CardsAndOfferEditCoupon',
        query: { mode: 'add', couponType }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* tab */
::v-deep {
	.el-tabs__header {
		margin-bottom: 0;
		background-color: #fff;
		border-radius: 0 0 5px 5px;
	}

	.el-tabs__nav-wrap::after {
		background-color: #fff;
	}

	.el-tabs__active-bar {
		height: 4px;
	}

	.el-row {
		flex-wrap: wrap;
	}

	.el-card,
	.el-card__body {
		height: 100%;
	}
}

/* 头部 */
.top {
	padding: 24px 30px 0;
	border-radius: 5px 5px;
	background-color: #fff;
	margin-bottom: 10px;

	.title {
		font-size: 20px;
	}
}

.empty-text {
	line-height: 60px;
	text-align: center;
	color: #909399;
	font-size: 14px;
}

/* create */
.create {
	width: 100%;
	min-height: 150px;
	overflow: hidden;

	.card {
		width: 250px;
		overflow: hidden;
		background-color: #f2f2f2;
		padding: 8px;
		box-sizing: border-box;
		border-radius: 8px;
		float: left;
		margin-right: 20px;

		.title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-weight: bold;
		}

		.p {
			margin-top: 20px;
		}
	}
}

/* 卡片 */
.coupon-card {
	margin-bottom: 20px;
	//height: 270px;
	cursor: pointer;
	position: relative;

	.coupon-labelType {
		position: absolute;
		top: 0;
		right: 15px;
		background-color: $primary;
		color: white;
		padding: 5px 10px;
	}

	.coupon-content {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100%;
	}

	.coupon-base {
		display: flex;

		.left {
			overflow: hidden;
			flex: 0 0 auto;
			width: 80px;
			height: 80px;
			margin-right: 15px;
			border-radius: 50%;
			border: 1px solid #e7e7e7;
		}

		.right {
			flex: 1 1 auto;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.name {
				font-size: 20px;
				// margin-top: 25px;
				font-weight: bold;
			}

			.type {
				margin-top: 5px;
				font-size: 14px;
				color: #909399;
			}
		}
	}

	.coupon-detail {
		text-align: center;
		border-bottom: 1px solid #e7e7e7;
		height: 90px;

		.cash,
		.discount,
		.exchange {
			font-size: 24px;
			margin-top: 10px;
			font-weight: bold;
		}

		.describe {
			margin-top: 10px;
			font-size: 14px;
			color: #909399;
		}
	}

	.coupon-more {
		margin-top: 10px;
		font-size: 14px;
		color: #909399;

		.date {
		}

		.belong {
		}
	}

	.coupon-status {
		margin-top: 10px;
		padding-top: 10px;
		border-top: 1px solid #e7e7e7;
		font-size: 14px;
	}
}
</style>
